# -*- coding: utf-8 -*-
import argparse
import os
from datetime import time
from ftplib import FTP
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import ThreadedFTPServer

import json
import FB_ALGO

class Task(object):
    task_id = 10

    def add(self):
        self.task_id += 11


task_id = 4396
filelist = []
user_hash = {}

def ftpconnect(host, port, username=None, password=None):
    ftp = FTP()
    ftp.connect(host, port)
    ftp.login(username, password)
    return ftp

# 从本地上传文件到ftp
def uploadfile(ftp, remotepath, localpath):
    bufsize = 1024
    fp = open(localpath, 'rb')
    ftp.storbinary('STOR ' + remotepath, fp, bufsize)
    ftp.set_debuglevel(0)
    fp.close()


class MyHandler(FTPHandler):

    def __init__(self, conn, server, ioloop=None):
        super().__init__(conn, server, ioloop)
        self.task_id = 0

    def on_connect(self):
        """when user connects to FTP Server, create uid and increase task id
        """
        #print("From %s:%s connected" % (self.remote_ip, self.remote_port))

        # 连接时加入字典
        global user_hash
        user_hash[self.remote_ip + str(self.remote_port)] = []

    def on_disconnect(self):
        # do something when client disconnects
        # 连接断开表示数据传输完毕
        # 用哈希表记录这次连接所上传的文件
        # 进行批量计算
        global user_hash
        #print(user_hash[self.remote_ip + str(self.remote_port)])
        files = user_hash[self.remote_ip + str(self.remote_port)]
        #for file in files:
        #    if file.endswith(".conf"):
        #        conffile = file
        #   else:
        #       conffile = "/FB/data/fb_params.conf"

        for file in files:
            print("[receive] --> " + file)
            # print(file)
            if file.endswith(".mat"):
                with open("/FB/data/fb_params.conf") as json_file:
                    conf = json.load(json_file)
                    if conf["current_algo"]=="fb_EEG_network":
                        print("[calmode] --> fb_EEG_network")
                        res = FB_ALGO.fb_EEG_network(file, "/FB/result_network", str(self.task_id))
                        print("[results] --> Network calculation success !")
                    else:
                        print("[calmode] --> fb_EEG_Power")
                        res = FB_ALGO.fb_EEG_Power(file, "/FB/result_power", str(self.task_id))
                        print("[results] --> Power calculation success !")

    def on_login(self, username):
        # do something when user login
        pass

    def on_logout(self, username):
        # do something when user logs out
        pass

    def on_file_sent(self, file):
        # do something when a file has been sent
        print(self.username, file)
        pass

    # 数据收到时做验证
    def on_file_received(self, file):
        """do something when a file has been received

        Args:
            file (string): file path
        """
        # print("[receive] --> "+self.username, file)

        # 连接时计数
        global task_id
        task_id += 11
        #print(task_id)
        self.task_id = task_id

        global user_hash
        user_hash[self.remote_ip + str(self.remote_port)].append(file)
        #res = FB_ALGO.fb_EEG_network(file, "/home/skye/FB/results", self.task_id)
        #print(res)

    def on_incomplete_file_sent(self, file):
        # do something when a file is partially sent
        # print("[sending] --> "+self.username, file)
        pass

    def on_incomplete_file_received(self, file):
        """remove partially uploaded files

        Args:
            file (string): file path
        """
        import os
        os.remove(file)


def main():
    authorizer = DummyAuthorizer()
    #设置用户和homedir为用户ftp传过来的目录
    authorizer.add_user('demo', 'demo', homedir=r'/FB/data/', perm='elradfmwMT')

    handler = MyHandler
    handler.authorizer = authorizer
    # multi，设置服务器监听地址和端口
    host = 'feedback.edu.cn'
    #port=2121
    server = ThreadedFTPServer((host, 2121), handler)

    # set a limit for connections
    server.max_cons = 8
    server.max_cons_per_ip = 2
    server.serve_forever()


if __name__ == "__main__":
    main()
